package com.jdk.demo.nio.charbuffer;

import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.Charset;

public class CharBuffer乱码问题 {

	public static void main(String[] args) throws UnsupportedEncodingException {
		m1();
		m2();
	}

	private static void m1() throws UnsupportedEncodingException {
		// 字节数组使用的编码为utf-8
		byte[] bytearrayIn1 = " 我是中国人 ".getBytes("utf-8");
		System.out.println(Charset.defaultCharset().name());

		ByteBuffer bytebuffer = ByteBuffer.wrap(bytearrayIn1);
		// 将bytebuffer中的内容转换成utf-8编码的CharBuffer
		CharBuffer charbuffer = Charset.forName("utf-8").decode(bytebuffer);
		System.out.println("bytebuffer=" + bytebuffer.getClass().getName());
		System.out.println("charbuffer=" + charbuffer.getClass().getName());
		System.out.println("bytebuffer capacity=" + bytebuffer.capacity() + ", position=" + bytebuffer.position() + " limit=" + bytebuffer.limit());
		System.out.println("charbuffer capacity=" + charbuffer.capacity() + ", position=" + charbuffer.position() + " limit=" + charbuffer.limit());

		charbuffer.position(0);
		for (int i = 0; i < charbuffer.limit(); i++) {
			System.out.print(charbuffer.get() + ",");
		}
		System.out.println();
	}

	private static void m2() throws UnsupportedEncodingException {
		// 字节数组使用的编码为utf-16BE
		byte[] bytearrayIn1 = " 我是中国人 ".getBytes("utf-16BE");
		System.out.println(Charset.defaultCharset().name());

		ByteBuffer bytebuffer = ByteBuffer.wrap(bytearrayIn1);
		// 将bytebuffer中的内容转换成utf-16BE编码的CharBuffer(CharBuffer的默认编码方式)
		CharBuffer charbuffer = bytebuffer.asCharBuffer();
		System.out.println("bytebuffer=" + bytebuffer.getClass().getName());
		System.out.println("charbuffer=" + charbuffer.getClass().getName());
		System.out.println("bytebuffer capacity=" + bytebuffer.capacity() + ", position=" + bytebuffer.position() + " limit=" + bytebuffer.limit());
		System.out.println("charbuffer capacity=" + charbuffer.capacity() + ", position=" + charbuffer.position() + " limit=" + charbuffer.limit());

		charbuffer.position(0);
		for (int i = 0; i < charbuffer.limit(); i++) {
			System.out.print(charbuffer.get() + ",");
		}
		System.out.println();
	}

}
